package com.zzedu.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.zzedu.common.annotation.Log;
import com.zzedu.common.core.controller.BaseController;
import com.zzedu.common.core.domain.AjaxResult;
import com.zzedu.common.core.page.TableDataInfo;
import com.zzedu.common.enums.BusinessType;
import com.zzedu.common.utils.ServletUtils;
import com.zzedu.common.utils.bean.BeanUtils;
import com.zzedu.common.utils.poi.ExcelUtil;
import com.zzedu.domain.OrderSumRenewVO;
import com.zzedu.domain.ZzChargeOrder;
import com.zzedu.dto.OrderSumDTO;
import com.zzedu.dto.ZzChargeOrderDTO;
import com.zzedu.service.IZzChargeOrderService;
import com.zzedu.service.IZzStuRenewOrderService;
import com.zzedu.vo.ZzChargeOrderVO;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 收费订单Controller
 *
 * @author Mr.Wang
 * @date 2025-10-15
 */
@RestController
@RequestMapping("/report/chargeorder")
public class ZzChargeOrderController extends BaseController {
    @Autowired
    private IZzChargeOrderService zzChargeOrderService;

    @Autowired
    private IZzStuRenewOrderService zzStuRenewOrderService;

    /**
     * 查询收费订单列表
     */
    @PreAuthorize("@permission.hasAnyPermissions('report:chargeorder:query')")
    @RequestMapping("/list")
    public TableDataInfo list(@RequestBody ZzChargeOrderDTO zzChargeOrder) {
        IPage<ZzChargeOrder> page = zzChargeOrderService.page(zzChargeOrder.getPageDTO(), zzChargeOrderService.buildQuery(zzChargeOrder));
        List<OrderSumRenewVO> sumRenewVOList = Lists.newArrayList();
        if (null != page && CollectionUtils.isNotEmpty(page.getRecords())) {
            OrderSumDTO query = new OrderSumDTO();
            query.setPageSize(-1L);
            query.setPageNum(-1L);
            query.setPayOrderId(page.getRecords().stream().map(ZzChargeOrder::getId).collect(Collectors.toList()));
            IPage<OrderSumRenewVO> sumPage = zzStuRenewOrderService.orderSumListPayOrder(query);
            sumRenewVOList.addAll(sumPage.getRecords());
        }
        page.setRecords(Lists.newArrayList());
        return getDataTable(page, sumRenewVOList);
    }

    /**
     * 月度报表
     *
     * @param zzChargeOrder
     * @return
     */
    @RequestMapping("/monthList")
    public TableDataInfo monthList(@RequestBody ZzChargeOrderDTO zzChargeOrder) {
        OrderSumDTO query = new OrderSumDTO();
        zzChargeOrder.setPageNum(-1L);
        zzChargeOrder.setPageSize(-1L);
        query.setPageSize(zzChargeOrder.getPageSize());
        query.setPageNum(zzChargeOrder.getPageNum());
        query.setSchoolIdList(zzChargeOrder.getSchoolIdArray());
        if (null != zzChargeOrder.getId()) {
            query.setPayOrderId(Lists.newArrayList(zzChargeOrder.getId()));
        }
        return getDataTable(zzStuRenewOrderService.orderSumListPayOrderToMonth(query));
    }

    /**
     * 导出收费订单列表
     */
    @PreAuthorize("@permission.hasAnyPermissions('report:chargeorder:export')")
    @Log(title = "收费订单", businessType = BusinessType.EXPORT)
    @RequestMapping("/export")
    public void export(ZzChargeOrderDTO zzChargeOrder) {
        zzChargeOrder.setPageNum(-1L);
        zzChargeOrder.setPageSize(-1L);
        IPage<ZzChargeOrder> page = zzChargeOrderService.page(zzChargeOrder.getPageDTO(), zzChargeOrderService.buildQuery(zzChargeOrder));
        List<OrderSumRenewVO> sumRenewVOList = Lists.newArrayList();
        Map<Long, BigDecimal> map = Maps.newHashMap();
        Map<Long, Integer> mapStuCountMap = Maps.newHashMap();
        if (null != page && CollectionUtils.isNotEmpty(page.getRecords())) {
            List<ZzChargeOrder> zzChargeOrderList = page.getRecords();
            List<List<ZzChargeOrder>> parationList = Lists.partition(zzChargeOrderList, 1000);
            for (List<ZzChargeOrder> chargeOrderList : parationList) {
                OrderSumDTO query = new OrderSumDTO();
                query.setPageSize(-1L);
                query.setPageNum(-1L);
                query.setPayOrderId(chargeOrderList.stream().map(ZzChargeOrder::getId).collect(Collectors.toList()));
                IPage<OrderSumRenewVO> sumPage = zzStuRenewOrderService.orderSumListPayOrder(query);
                sumRenewVOList.addAll(sumPage.getRecords());
                for (ZzChargeOrder order : chargeOrderList) {
                    map.put(order.getId(), order.getFee());
                    mapStuCountMap.put(order.getId(), order.getStuCount());
                }
            }
        }
        List<ZzChargeOrderVO> zzChargeOrderVOList = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(sumRenewVOList)) {
            for (OrderSumRenewVO orderSumRenewVO : sumRenewVOList) {
                ZzChargeOrderVO zzChargeOrderVO = new ZzChargeOrderVO();
                BeanUtils.copyBeanProp(zzChargeOrderVO, orderSumRenewVO);
                zzChargeOrderVO.setLinkMan(orderSumRenewVO.getContacts());
                zzChargeOrderVO.setAmount(new BigDecimal(orderSumRenewVO.getOrderAmount()));
                zzChargeOrderVO.setAddStuAmount(new BigDecimal(orderSumRenewVO.getAddStuAmount()));
                zzChargeOrderVO.setRenewStuAmount(new BigDecimal(orderSumRenewVO.getRenewStuAmount()));
                zzChargeOrderVO.setFee(map.get(orderSumRenewVO.getBillId()));
                zzChargeOrderVO.setStuCount(mapStuCountMap.get(orderSumRenewVO.getBillId()));
                zzChargeOrderVOList.add(zzChargeOrderVO);
            }
        }
        ExcelUtil<ZzChargeOrderVO> util = new ExcelUtil<ZzChargeOrderVO>(ZzChargeOrderVO.class);
        util.exportExcel(ServletUtils.getResponse(), zzChargeOrderVOList, "账单列表");
    }

    /**
     * 获取收费订单详细信息
     */
    @PreAuthorize("@permission.hasAnyPermissions('report:chargeorder:query')")
    @RequestMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(zzChargeOrderService.getById(id));
    }

    /**
     * 确认收款
     */
    @PreAuthorize("@permission.hasAnyPermissions('report:chargeorder:confirm')")
    @Log(title = "收费订单", businessType = BusinessType.UPDATE)
    @RequestMapping("/confirm/{ids}")
    public AjaxResult confirm(@PathVariable List<Long> ids) {
        return toAjax(zzChargeOrderService.confirm(ids));
    }
}
